#include "./bsp_clk.h"
void pll1_clk_init(void)
{
    CCM->CCSR |= (1<<2);//设置PLL时钟为 step_clk (24M晶振时钟)
    CCM_ANALOG->PLL_ARM |=(1<<13);//使能PLL1
    CCM_ANALOG->PLL_ARM |=0x00000058;//设置PLL1(pll1_main_clk)时钟频率为1056M
    CCM->CCSR |= (1<<2);//设置PLL1时钟 pll1_main_clk
    CCM->CACRR = 0x00000001;//设置PLL1时钟二分频给ARM内核（528）MHz
}
/* 设置PLL2(SYS PLL)各个PFD */
void pll2_clk_init(void)
{
    unsigned int reg = 0;
    	
	reg = CCM_ANALOG->PFD_528;
	reg &= ~(0X3F3F3F3F);		/* 清除原来的设置 						*/
	reg |= 32<<24;				/* PLL2_PFD3=528*18/32=297Mhz 	*/
	reg |= 24<<16;				/* PLL2_PFD2=528*18/24=396Mhz(DDR使用的时钟，最大400Mhz) */
	reg |= 16<<8;				/* PLL2_PFD1=528*18/16=594Mhz 	*/
	reg |= 27<<0;				/* PLL2_PFD0=528*18/27=352Mhz  	*/
	CCM_ANALOG->PFD_528=reg;	/* 设置PLL2_PFD0~3 		 		*/
}

/* 设置PLL3(USB1)各个PFD */
void pll3_clk_init(void)
{
    unsigned int reg = 0;   
	reg = 0;					/* 清零   */
	reg = CCM_ANALOG->PFD_480;
	reg &= ~(0X3F3F3F3F);		/* 清除原来的设置 							*/
	reg |= 19<<24;				/* PLL3_PFD3=480*18/19=454.74Mhz 	*/
	reg |= 17<<16;				/* PLL3_PFD2=480*18/17=508.24Mhz 	*/
	reg |= 16<<8;				/* PLL3_PFD1=480*18/16=540Mhz		*/
	reg |= 12<<0;				/* PLL3_PFD0=480*18/12=720Mhz	 	*/
	CCM_ANALOG->PFD_480=reg;	/* 设置PLL3_PFD0~3 					*/	
}
/*设置AHB时钟 最小6Mhz， 最大132Mhz (boot rom自动设置好了可以不用设置)*/
void ahb_clk_init(void)
{
	CCM->CBCMR &= ~(3 << 18); 	/* 清除设置*/ 
	CCM->CBCMR |= (1 << 18);	/* pre_periph_clk=PLL2_PFD2=396MHz */
	CCM->CBCDR &= ~(1 << 25);	/* periph_clk=pre_periph_clk=396MHz */
	while(CCM->CDHIPR & (1 << 5));/* 等待握手完成 */
}
/*设置IPG_CLK_ROOT最小3Mhz，最大66Mhz (boot rom自动设置好了可以不用设置)*/
void ipg_clk_init(void)
{
	CCM->CBCDR &= ~(3 << 8);	/* CBCDR的IPG_PODF清零 */
	CCM->CBCDR |= 1 << 8;		/* IPG_PODF 2分频，IPG_CLK_ROOT=66MHz */
}
/*设置PERCLK_CLK_ROOT时钟 */
void per_clk_init(void)
{
	CCM->CSCMR1 &= ~(1 << 6);	/* PERCLK_CLK_ROOT时钟源为IPG */
	CCM->CSCMR1 &= ~(7 << 0);	/* PERCLK_PODF位清零，即1分频 */
}
/*所有外设时钟全部使能*/
void clk_drive_enable(void)
{
    CCM->CCGR1 = 0XFFFFFFFF; //开启时钟
    CCM->CCGR2 = 0XFFFFFFFF; //开启时钟
    CCM->CCGR3 = 0XFFFFFFFF; //开启时钟
    CCM->CCGR4 = 0XFFFFFFFF; //开启时钟
    CCM->CCGR5 = 0XFFFFFFFF; //开启时钟
    CCM->CCGR6 = 0XFFFFFFFF; //开启时钟
}
void clk_init(void)
{
    pll1_clk_init();
    pll2_clk_init();
    pll3_clk_init();
	ahb_clk_init();
	ipg_clk_init();
	per_clk_init();
    clk_drive_enable();//使能所有时钟
}

void delay_short(volatile unsigned int n)
{
	while(n--){}
}
/*
 * @description	: 延时函数,在396Mhz的主频下
 * 			  	  延时时间大约为1ms
 * @param - n	: 要延时的ms数
 * @return 		: 无
 */
void bsp_delay_ms(volatile unsigned int n)
{
	while(n--){
		delay_short(0x7ff);
	}
}